import os
import time

from django.template import loader
from django.conf import settings

from apps.contents.models import ContentCategory
from apps.contents.utils import get_categories


def generate_static_index_html():

    print('定时任务:%s: generate_static_index_html' % time.ctime())

    # 1. 获取对应的数据
    # 1.获取 商品分类数据
    categories = get_categories()
    # 2.获取广告数据
    contents = {}
    # 1. 获取所有的 广告分类 ContentCategory
    content_categories = ContentCategory.objects.all()
    # 2. 遍历广告分类
    for cat in content_categories:
        # 3. 根据分类 获取 对应 广告内容 Content==1:n
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
    # 8.构建前端数据
    context = {
        'categories': categories,
        'contents': contents
    }

    # 2. 获取对应的模板
    template = loader.get_template('index.html')

    # 3. 将数据 和 模板 == 渲染-->string
    html_txt = template.render(context)

    # 4. 存入到 静态服务的文件中
    filepath = os.path.join(os.path.dirname(os.path.dirname(settings.BASE_DIR)), 'front_end_pc/index.html')
    print(filepath)
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(html_txt)